package com.software.myopiachildren;

import android.Manifest;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.software.myopiachildren.adapter.MainFragmentAdapter;
import com.software.myopiachildren.base.BaseActivity;
import com.software.myopiachildren.bean.BaseInfo;
import com.software.myopiachildren.content.Constant;
import com.software.myopiachildren.fragment.ConnectFragment;
import com.software.myopiachildren.fragment.SetFragment;
import com.software.myopiachildren.http.HostType;
import com.software.myopiachildren.http.HttpApi2;
import com.software.myopiachildren.service.LocalService;
import com.software.myopiachildren.service.SensorService;
import com.software.myopiachildren.ui.WebViewActivity;
import com.software.myopiachildren.utils.AppUtil;
import com.software.myopiachildren.utils.NotificationUtils;
import com.software.myopiachildren.utils.ToastUtil;
import com.software.myopiachildren.utils.perm.NetworkUtils;
import com.software.myopiachildren.utils.perm.PermissionsUtils;
import com.software.myopiachildren.utils.sp.SP;
import com.software.myopiachildren.view.SlideViewPager;
import com.software.myopiachildren.view.dialog.CustomizeDialog;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.download.DownloadListener;
import com.tencent.bugly.beta.download.DownloadTask;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActivity";

    @BindView(R.id.vp_main_content)
    SlideViewPager mVp;
    @BindView(R.id.rb_item1)
    RadioButton mRb1;
    @BindView(R.id.rb_item2)
    RadioButton mRb2;
    @BindView(R.id.rg_main)
    RadioGroup mRg;

    private List<Fragment> mFragment = new ArrayList<>();

    // 用户协议、隐私政策
    private boolean isCheckPrivacy = false;
    private long versionCode;
    private long currentVersionCode;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        // Fragment操作
        mFragment.add(new ConnectFragment());
        mFragment.add(new SetFragment());
        mVp.setOffscreenPageLimit(mFragment.size());
        mVp.setAdapter(new MainFragmentAdapter(getSupportFragmentManager(), mFragment));
        initListener();

    }

    @Override
    public void initData() {
        getVersionDownload(); // 新版本下载
        getCheckVersion(); // 检查版本更新
        getPermissions();  // 权限管理
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    /**
     * 底部监听事件
     */
    private void initListener() {
        mRg.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_item1:
                    mVp.setCurrentItem(0);
                    mRg.setBackgroundColor(getResources().getColor(R.color.color_bg_style1));
                    break;

                case R.id.rb_item2:
                    mVp.setCurrentItem(1);
                    mRg.setBackgroundColor(getResources().getColor(R.color.color_bg_style));
                    break;
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getSupportFragmentManager().getFragments();
        if (getSupportFragmentManager().getFragments().size() > 0) {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            for (Fragment mFragment : fragments) {
                mFragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }


    /**
     * 发送警报
     */
    private void getAlert() {
        String device_code = new SP().load(Constant.DEVICE_CODE, "");
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(MainActivity.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", device_code);
            params.put("type", 1 + "");

            HttpApi2.getApiService(HostType.TELE_CONFIG).getAlert(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }

    /**
     * 激活设备
     */
    private void getActivateDevice() {
        String device_code = new SP().load(Constant.DEVICE_CODE, "");
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(MainActivity.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", device_code);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getActivateDevice(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }


    // 再按一次退出
    private long mExitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.showShort(getResources().getString(R.string.s_btn_exit));
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /*****  权限管理、版本管理start *****/
    /**
     * 权限管理
     */
    private void getPermissions() {
        // 权限管理（设置需要打开的所有权限）
        String[] permissions = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_EXTERNAL_STORAGE, // 读取内存权限
                Manifest.permission.WRITE_EXTERNAL_STORAGE}; // 写入内存权限
//        PermissionsUtils.showSystemSetting = false;//是否支持显示系统设置权限设置窗口跳转
        //这里的this不是上下文，是Activity对象！
        PermissionsUtils.getInstance().chekPermissions(this, permissions, permissionsResult);
    }

    //创建监听权限的接口对象（权限设置）
    PermissionsUtils.IPermissionsResult permissionsResult = new PermissionsUtils.IPermissionsResult() {
        @Override
        public void passPermissons() {
            Log.e(TAG, "====:权限通过，开始操作");
            // （权限通过后）开始操作

            // 开启sensor传感器服务
            startService(new Intent(MainActivity.this, SensorService.class));
            // 开启后台进程守护
            startService(new Intent(MainActivity.this, LocalService.class));

            checkPrivacy(); // 用户协议

        }

        @Override
        public void forbitPermissons() {
            Log.e(TAG, "====:权限不通过，重新授权");
//            finish();
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //就多一个参数this
        PermissionsUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    // 检查新版本
    private void getCheckVersion() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Beta.strToastYourAreTheLatestVersion = "";
                Beta.checkUpgrade();
            }
        }, 700);
    }

    // 版本下载更新
    private void getVersionDownload() {
        Beta.registerDownloadListener(new DownloadListener() {
            @Override
            public void onReceive(DownloadTask downloadTask) {
                Timber.tag(Constant.TAG).e("onReceive");
                NotificationUtils.notificationMsg(MainActivity.this, Constant.VERSION_UPGRADE + "", getResources().getString(R.string.app_name),
                        getResources().getString(R.string.s_version_download) + (int) (downloadTask.getSavedLength() * 100 / downloadTask.getTotalLength()) + "%", null);
            }

            @Override
            public void onCompleted(DownloadTask downloadTask) {
                Timber.tag(Constant.TAG).e("onCompleted:" + downloadTask.getSaveFile());
                PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, getInstallIntent(downloadTask.getSaveFile()), 0);
                NotificationUtils.notificationMsg(MainActivity.this, Constant.VERSION_UPGRADE + "", getResources().getString(R.string.app_name),
                        getResources().getString(R.string.s_version_download_success), pi);
            }

            @Override
            public void onFailed(DownloadTask downloadTask, int i, String s) {
                Timber.tag(Constant.TAG).e("onFailed" + s);
                NotificationUtils.notificationMsg(MainActivity.this, Constant.VERSION_UPGRADE + "", getResources().getString(R.string.app_name),
                        getResources().getString(R.string.s_version_download_failure), null);
            }
        });
    }

    private Intent getInstallIntent(File saveFile) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileProvider", saveFile);//在AndroidManifest中的android:authorities值
            install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            install.setDataAndType(Uri.fromFile(saveFile), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        return install;
    }

    /*****  权限管理、版本管理stop *****/


    /**
     * 显示隐私政策或跳转到其他界面
     */
    private void checkPrivacy() {

        //先判断是否显示了隐私政策
        currentVersionCode = AppUtil.getAppVersionCode(MainActivity.this);
        versionCode = new SP().load(Constant.SP_VERSION_CODE, 0L);
        isCheckPrivacy = new SP().load(Constant.SP_PRIVACY, false);

        if (!isCheckPrivacy || versionCode != currentVersionCode) {
            showPrivacy();
        } else {
//            ToastUtil.showShort(getString(R.string.confirmed));
        }
    }

    /**
     * 显示用户协议和隐私政策
     */
    private void showPrivacy() {
        final CustomizeDialog dialog = new CustomizeDialog(this, R.style.DialogUtilStyle);
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                TextView tv_note = (TextView) dialog.findViewById(R.id.tv_note);
                TextView tv_privacy_tips = (TextView) dialog.findViewById(R.id.tv_privacy_tips);
                TextView tv_cancel = (TextView) dialog.findViewById(R.id.tv_cancel);//取消
                TextView tv_confirm = (TextView) dialog.findViewById(R.id.tv_confirm);//确认


                String string = getResources().getString(R.string.privacy_tips);
                String key1 = getResources().getString(R.string.privacy_tips_key1);
                String key2 = getResources().getString(R.string.privacy_tips_key2);
                int index1 = string.indexOf(key1);
                int index2 = string.indexOf(key2);

                //需要显示的字串
                SpannableString spannedString = new SpannableString(string);
                //设置点击字体颜色
                ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(getResources().getColor(R.color.color_F7CB66));
                spannedString.setSpan(colorSpan1, index1, index1 + key1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                ForegroundColorSpan colorSpan2 = new ForegroundColorSpan(getResources().getColor(R.color.color_F7CB66));
                spannedString.setSpan(colorSpan2, index2, index2 + key2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                //设置点击字体大小
                AbsoluteSizeSpan sizeSpan1 = new AbsoluteSizeSpan(16, true);
                spannedString.setSpan(sizeSpan1, index1, index1 + key1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                AbsoluteSizeSpan sizeSpan2 = new AbsoluteSizeSpan(16, true);
                spannedString.setSpan(sizeSpan2, index2, index2 + key2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                //设置点击事件
                ClickableSpan clickableSpan1 = new ClickableSpan() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
                        intent.putExtra("url", Constant.URL + Constant.YHXY_VIEW);
                        intent.putExtra("type", 1);
                        startActivity(intent);
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        //点击事件去掉下划线
                        ds.setUnderlineText(false);
                    }
                };
                spannedString.setSpan(clickableSpan1, index1, index1 + key1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

                ClickableSpan clickableSpan2 = new ClickableSpan() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
                        intent.putExtra("url", Constant.URL + Constant.YSZC_VIEW);
                        intent.putExtra("type", 2);
                        startActivity(intent);
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        //点击事件去掉下划线
                        ds.setUnderlineText(false);
                    }
                };
                spannedString.setSpan(clickableSpan2, index2, index2 + key2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

                //设置点击后的颜色为透明，否则会一直出现高亮
                tv_privacy_tips.setHighlightColor(Color.TRANSPARENT);
                //开始响应点击事件
                tv_privacy_tips.setMovementMethod(LinkMovementMethod.getInstance());
                tv_privacy_tips.setText(spannedString);


                //取消
                tv_cancel.setOnClickListener(v -> {
                    new SP().save(Constant.SP_VERSION_CODE, currentVersionCode);
                    new SP().save(Constant.SP_PRIVACY, false);
                    finish();
                    dialog.dismiss();

                });

                //确认
                tv_confirm.setOnClickListener(v -> {
                    new SP().save(Constant.SP_VERSION_CODE, currentVersionCode);
                    new SP().save(Constant.SP_PRIVACY, true);
                    ToastUtil.showShort(getString(R.string.confirmed));
                    dialog.dismiss();
                });
            }
        });
        dialog.showDialog(R.layout.dialog_privacy);
    }


}